from flask import Flask
from flask_sock import Sock
import json

app = Flask(__name__)
sock = Sock(app)


# Flask路由
@app.route('/')
def hello():
    return "Hello, World!"


@sock.route('/chat')
def chat(ws):
    try:
        while True:
            message = ws.receive()
            try:
                input_message = json.loads(message)
                print(f"Received message: {input_message}")
                ws.send("websocketSuccess")
            except json.JSONDecodeError:
                print("Received message is not valid JSON")
                continue
    except Exception as e:
        print(f"An error occurred: {e}")


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=False)
